<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Db;
use think\Exception;
use think\Log;

class Leshua  extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    //微信
    public function wx($res,$pay)
    {
        //②、统一下单
        $dizhi = 'http://'.$this->request->host();
        $notifyUrl = $dizhi."/index/leshua/yibu/sid/".$res['id'].'/channel_id/'.$pay['id'];// 替换为您的支付回调通知地址
        $openId = '';
        // 微信支付配置
        $appId = ""; //
        $json = json_decode($pay['json']);
        $mchId = $json->mid; // 替换为您的商户号
        $apiKey = $json->key; // 替换为您的API密钥
        $tradeType = "JSAPI";
        // 构建统一下单请求参数
        $data = $this->buildUnifiedOrderData($appId, $mchId, $apiKey, $tradeType, $notifyUrl, $openId,$res);
        $result = $this->post1($data);
        $xml = simplexml_load_string($result, null, LIBXML_NOCDATA);
        $result = json_decode(json_encode($xml), true);
        if (!$result || !isset($result['jspay_url'])) {  //失败处理
            dump($result['resp_msg']);die;
        } else {    //成功处理
            $jsApiParameters = $result['jspay_url'];
            return $jsApiParameters;
        }
    }
    //异步通知
    public function yibu()
    {
        $xml_data = file_get_contents('php://input');
        Log::record('回调参数', $xml_data);
        $xml = simplexml_load_string($xml_data, null, LIBXML_NOCDATA);
        $result = json_decode(json_encode($xml), true);
        // 启动事务
        Db::startTrans();
        try{
            $params = request()->param();
            $jiaofei_type = 1;
            //修改数据
            Db::name('list_one')
                ->where(['id'=>$params['sid']])
                ->update([
                    'jiaofei'=>2,
                    'jiaofei_price'=>$result['amount']/100,
                    'jiaofei_time'=>date("Y-m-d H:i:s",time()),
                    'jiaofei_type'=>$jiaofei_type,
                    'qianzi_status'=>5
                ]);
            $channel_id = $params['channel_id'];
            $model = new Index();
            $model->num($params['sid'],$channel_id);

            // 提交事务
            Db::commit();
            return "000000";
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $c = $e->getMessage();
            echo $c;
        }
    }



    // 构建统一下单请求参数
    public function buildUnifiedOrderData($appId, $mchId, $apiKey, $tradeType, $notifyUrl, $openid,$res)
    {
        $nonceStr = md5(uniqid()); // 生成随机字符串
        if($res['type'] == 2){
            $res['tong_storage'] = $res['tong_storage'].'2';
        }
        $data = array(
            "merchant_id" => $mchId,
            "third_order_id" => "hngs".$this->third_order_id(), // 替换为您的订单号
            "timestamp" => time(),
            "amount"=>strval($res['main_free']*100),
            "pay_way"=>"WXZF",
            "jspay_flag"=>"2",
            "body"=>$res['car_num'],
            "goods_detail"=>$res['car_num'],
            "notify_url" => $notifyUrl,
            "service"=>"get_tdcode",
            "nonce_str"=>$this->generateOrderNumber(),
        );
        $data["sign"] = $this->generateSignature($apiKey, $data); // 生成签名
        return $data;
    }
    function third_order_id() {
        $timestamp = time(); // 当前时间戳
        $random = mt_rand(1000, 9999); // 生成一个 4 位随机数
        $orderNumber = $timestamp . $random; // 拼接时间戳和随机数
        return $orderNumber;
    }
    function generateOrderNumber() {
        $timestamp = time(); // 当前时间戳
        $random = mt_rand(1000, 9999); // 生成一个 4 位随机数

        $array1 = array(0,1,2,3,4,5,6,7,8,9,'q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m','Q','W','E','R','T','Y','U','I','O','P','M','N','B','V','C','X','Z','A','S','D','F','G','H','J','K','L');
        $i= 0;
        $str = null;
        while ( $i<= 21) {
            $str .= $array1[array_rand($array1,1)];
            $i++;

        }
        $orderNumber = $timestamp . $str; // 拼接时间戳和随机数
        return $orderNumber;
    }
    // 生成请求的签名
    public function generateSignature($apiKey, $data)
    {
        ksort($data); // 按键名进行升序排序

        $signData = '';
        foreach ($data as $key => $value) {
            $signData .= $key . '=' . $value . '&';
        }
        $signData .= 'key=' . $apiKey;

        return hash('MD5', $signData); // 使用HMAC-SHA256进行签名
    }
    public function post1($postData)
    {
        $url = "https://paygate.leshuazf.com/cgi-bin/lepos_pay_gateway.cgi";
        $jsonData = json_encode($postData);
        // dump($url);die;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json'
        ));
        // 发送请求并获取响应
        $response = curl_exec($ch);

        return $response;
    }


}